﻿using UnityEditor;
using UnityEngine;

namespace HKTools
{
    /// <summary>
    /// HK_TargetCam 中 Target枚举值唯一性检测的属性
    /// </summary>
    public class TargetUniqueAttribute : PropertyAttribute
    {

    }

#if UNITY_EDITOR
    [CustomPropertyDrawer(typeof(TargetUniqueAttribute))]
    public class TargetUniqueDrawer : PropertyDrawer
    {
        bool isUnique = true;

        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            HK_BaseTarget curTarget = property.serializedObject.targetObject as HK_BaseTarget;

            HK_BaseTarget[] allTargets = Object.FindObjectsByType<HK_BaseTarget>(FindObjectsSortMode.InstanceID);

            foreach (HK_BaseTarget target in allTargets)
            {
                if (curTarget == target)
                {
                    continue;
                }

                SerializedProperty otherProperty = new SerializedObject(target).FindProperty(property.propertyPath);

                //Debug.Log(curTarget.Equals(target));

                if (otherProperty != null && otherProperty.enumValueIndex == property.enumValueIndex)
                {
                    isUnique = false;
                    break;
                }
                else
                {
                    isUnique = true;
                }

                isUnique = true;
            }

            Color originalColor = GUI.backgroundColor;

            if (!isUnique)
            {
                GUI.backgroundColor = Color.red;
            }

            EditorGUI.PropertyField(position, property, label);

            GUI.backgroundColor = originalColor;

            if (!isUnique)
            {
                // 调整帮助文本框的位置，使其位于枚举字段下方,增加了一行的高度和一些垂直间距
                position.y += EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing;
                EditorGUI.HelpBox(position, $"{property.displayName} 的值在其Target中已存在！请确保唯一性！", MessageType.Error);

                GUILayout.Space(10);
            }
        }

        public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
        {
            // 默认情况下，属性的高度是单行高度
            float propertyHeight = EditorGUIUtility.singleLineHeight;

            // 如果枚举值不唯一，我们需要增加额外的高度来容纳帮助文本框
            // 这里简化处理，总是假设不唯一，实际使用时应根据isUnique的实际值来决定
            if (!isUnique)
            {
                // 增加一个额外行的高度和一些垂直间距来容纳帮助文本框
                propertyHeight += EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing;
            }

            return propertyHeight;
        }
    }
#endif
}